<?php

namespace app\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Request;
use app\model\Site;
use app\utils\Utils;
use app\utils\Adminapi;
use Throwable;
use app\model\Log;


class Admin extends BaseController
{
    public function index() // 首页
    {
        $admin = Utils::get_admin();
        if ($admin == false) {
            http_response_code(404);
            return View::fetch(Site::get('template') . '/404');
        }
        return View::fetch('admin/index');
    }

    public function apilod($path) // API
    {
        $con = AdminAPI::{$path}();
        try {
            $admin = Utils::get_admin();
            if ($admin == false) {
                http_response_code(404);
                return View::fetch(Site::get('template') . '/404');
            }


            if ($con === false) {
                http_response_code(404);
                return json(array(
                    "code" => 404
                ));
            }

            return $con;
        } catch (Throwable $e) {
            return json(array(
                "code" => 500
            ));
        }
    }

    public function page() // 页面
    {
        $path = Request::get("a");
        if (Utils::has_admin($path)  || $path == "home") {
            return '<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/mdui@1.0.2/dist/css/mdui.min.css" />
<script src="https://fastly.jsdelivr.net/npm/mdui@1.0.2/dist/js/mdui.min.js"></script>
<link rel="stylesheet" href="/admin_static/beautify.css" />
<link rel="stylesheet" href="/admin_static/iframe.css" />
<script src="/admin_static/dialog.js"></script>
<script src="/admin_static/iframe.js"></script>
<script src="/admin_static/table.js"></script>' . View::fetch("admin/pages/" . $path);
        } else {
            http_response_code(404);
            return View::fetch(Site::get('template') . '/404');
        }
    }

    public function get_template() // 页面
    {
        $dir = '../view/'; // 目标目录

        // 获取目录中的所有文件和文件夹
        $files = scandir($dir);
        $list = array();
        // 遍历文件和文件夹
        foreach ($files as $file) {
            if (is_dir($dir . $file) && $file != '.' && $file != '..') {
                $list[] = $file;
            }
        }
        if (isset($list['page'])) {
            unset($list['page']);
        }
        unset($list['admin']);
        return json(array('code' => 200, 'data' => $list));
    }
}
